const { ROLES, ROLE_LEVELS, ROLE_NAMES } = require('../constants/roles');
const XLSX = require('xlsx');
const UserService = require('../services/userService');
const AuthHelper = require('../utils/authHelper');


// 登录接口
const login = async (req, res) => {
  try {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(200).json({
        code: 500,
        message: '用户名和密码不能为空'
      });
    }

    const user = await UserService.login(username, password);
    const token = AuthHelper.generateToken({ username: user.username });
    const userInfo = AuthHelper.sanitizeUser(user);

    return res.status(200).json({
      code: 200,
      message: '登录成功',
      token,
      userinfo: userInfo
    });

  } catch (error) {
    console.error('登录错误:', error);
    return res.status(500).json({
      code: 500,
      message: error.message || '服务器错误'
    });
  }
};

// 注册接口
const register = async (req, res) => {
  try {
    const { username, password, email, phone, nickname, role } = req.body;
    
    // 基础验证
    if (!username || !password) {
      return res.status(200).json({
        code: 500,
        message: '用户名和密码不能为空'
      });
    }

    // 验证角色是否有效
    if (!Object.values(ROLES).includes(role)) {
      return res.status(200).json({
        code: 500,
        message: '无效的角色类型'
      });
    }

    const savedUser = await UserService.register({
      username,
      password,
      email,
      phone,
      nickname,
      role
    });

    const userResponse = AuthHelper.sanitizeUser(savedUser);
    return res.status(200).json({
      code: 200,
      message: '注册成功',
      data: userResponse
    });

  } catch (error) {
    console.error('注册错误:', error);
    return res.status(200).json({
      code: 500,
      message: error.message || '注册失败'
    });
  }
};
const updateUser = async (req, res) => {
  try {
    const { userId } = req.params;
    const updateData = req.body;

    if (Object.keys(updateData).length === 0) {
      return res.status(200).json({
        code: 500,
        message: '没有提供需要更新的字段'
      });
    }

    const updatedUser = await UserService.updateUser(userId, updateData);
    return res.status(200).json({
      code: 200,
      message: '更新成功',
      data: AuthHelper.sanitizeUser(updatedUser)
    });

  } catch (error) {
    console.error('更新用户信息错误:', error);
    return res.status(500).json({
      code: 500,
      message: error.message || '更新用户信息失败'
    });
  }
};

// 获取用户列表接口
const getAllUsers = async (req, res) => {
  try {
    const result = await UserService.getUsers(req.body);

    res.status(200).json({
      code: 200,
      message: 'Success',
      data: result
    });

  } catch (error) {
    console.error('[Error] getAllUsers:', error);
    
    // 7. 错误分类处理
    let statusCode = 500;
    let message = '服务器内部错误';

    if (error.name === 'CastError') {
      statusCode = 400;
      message = '参数类型错误';
    }

    res.status(statusCode).json({ 
      code: statusCode, 
      message 
    });
  }
};

// 获取用户信息接口
const getUserProfile = async (req, res) => {
  try {
    const { username } = req.user;
    const user = await UserService.getUserProfile(username);
    return res.status(200).json({
      code: 200,
      message: '获取成功',
      data: user
    });

  } catch (error) {
    console.error('获取用户信息错误:', error);
    return res.status(200).json({
      code: 500,
      message: error.message || '获取用户信息失败'
    });
  }
};

// 删除用户接口
const deleteUser = async (req, res) => {
  try {
    const { userId } = req.params;
    const currentUser = req.user;
    await UserService.deleteUser(userId, currentUser);
    
    return res.status(200).json({
      code: 200,
      message: '删除成功',
      data: { id: userId }
    });

  } catch (error) {
    console.error('删除用户错误:', error);
    return res.status(200).json({
      code: 500,
      message: error.message || '删除用户失败'
    });
  }
};

// 获取角色列表接口
const getRoles = async (req, res) => {
  try {
    const roles = await UserService.getRoles();
    
    return res.status(200).json({
      code: 200,
      message: '获取成功',
      data: roles
    });

  } catch (error) {
    console.error('获取角色列表错误:', error);
    return res.status(200).json({
      code: 500,
      message: error.message || '获取角色列表失败'
    });
  }
};


const exportUsers = async (req, res) => {
  try {
    const { ids } = req.query;
    const fileBuffer = await UserService.exportUsers(ids);
    
    const fileName = encodeURIComponent('用户列表.xlsx');
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
    res.send(fileBuffer);

  } catch (error) {
    console.error('导出用户错误:', error);
    return res.status(500).json({
      code: 500,
      message: error.message || '导出用户失败'
    });
  }
};




module.exports = {
  login,
  register,
  getAllUsers,
  getUserProfile,
  deleteUser,
  getRoles,
  updateUser,
  exportUsers
};
